package cn.hengzhu.main_manager.web.controller;

import cn.hengzhu.main_manager.repository.dao.*;
import cn.hengzhu.main_manager.repository.domain.*;
import cn.hengzhu.main_manager.repository.param.BoxUseRecordParam;
import cn.hengzhu.main_manager.repository.param.CaseBoxListParam;
import cn.hengzhu.main_manager.repository.param.CaseListParam;
import cn.hengzhu.main_manager.repository.param.ChangeCaseParam;
import cn.hengzhu.main_manager.repository.vo.BoxAllInfoVO;
import cn.hengzhu.main_manager.repository.vo.BoxUseRecordVO;
import cn.hengzhu.main_manager.repository.vo.CaseBoxListVO;
import cn.hengzhu.main_manager.repository.vo.CaseVO;
import cn.hengzhu.main_manager.service.ManageCaseBoxService;
import cn.hengzhu.main_manager.service.ManageCaseService;
import cn.hengzhu.main_manager.utils.*;
import cn.hengzhu.main_manager.utils.ann.SystemControllerLog;
import cn.hengzhu.main_manager.utils.config.AllConst;
import cn.hengzhu.main_manager.utils.config.RbMsgCommand;
import cn.hengzhu.main_manager.utils.config.gzh.WeiXinConst;
import cn.hengzhu.main_manager.utils.consts.CaseUseTypeConst;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/main")
public class CaseController {

	@Autowired
	private ManageCaseMapper manageCaseMapper;
	@Autowired
	private ManageCaseBoxMapper manageCaseBoxMapper;
	@Autowired
	private AccessRecordMapper accessRecordMapper;
	@Autowired
	private ManageCompMapper manageCompMapper;
	@Autowired
	private ManageCaseBoxService manageCaseBoxService;
	@Autowired
	private SysConstMapper sysConstMapper;
	@Autowired
	private ManageCaseService manageCaseService;
	@Autowired
	private ManageCaseTypeMapper manageCaseTypeMapper;
	@Autowired
	private ManageCaseUsetimeMapper manageCaseUsetimeMapper;

	/**
	 * 存储柜列表
	 */
	@ResponseBody
	@RequestMapping(value = "/getCaseList", method = RequestMethod.GET)
	public LayUiResultJson<CaseVO> getCaseList(CaseListParam param, Model model) {
		List<CaseVO> list = new ArrayList<>();
		//从shiro获取当前登录session中的用户信息
		ManageUser user = UserContext.getUser();
		Integer compId = user.getCompId(); //公司id

		Byte useType2 = param.getUseTypeId(); //用途
		String like = param.getLike(); //模糊搜索
		Byte isOnline = param.getIsOnline(); //是否在线

		Integer selectCompId = compId;
		// 用户登录的公司id是否为0（为0你就可以传入任意公司的id来查询出） 为0则赋值为传入的公司id默认为-1
		if (compId == 0) {
			selectCompId = param.getCompId();
		}
		// 公司列表
		List<ManageCase> manageCaseList = new ArrayList<>();
		// compId==-1为查询所有公司 useType==0 为查询全部用途
		ManageCaseExample manageCaseExample = new ManageCaseExample();
		ManageCaseExample.Criteria criteria = manageCaseExample.createCriteria();

		//用途 不传则查询所有的柜子
		if (useType2 != 0) {
			criteria.andUseTypeEqualTo(useType2);
		}

		//用户公司id为0 且没有传这个参数则为-1 实则每次and这个都会被添加到 protected List<Criterion> criteria; 这个list中
		if (selectCompId != -1) {
			criteria.andCompIdEqualTo(selectCompId);
		}

		//查询是否在线的柜子 没传默认为-1 查询所有柜子
		if (isOnline != -1) {
			criteria.andIsOnlineEqualTo(isOnline);
		}

		criteria.andCaseNoLike(like);

		// 查询本公司的储物柜列表
		PageHelper.startPage(param.getPage(), param.getLimit(), true);
		manageCaseList = manageCaseMapper.selectByExample(manageCaseExample);
		System.out.println(manageCaseList);
		//用户公司的柜子数为空 或者为null 直接返回
		if(manageCaseList==null || manageCaseList.isEmpty()){
			return new LayUiResultJson<>(0, list);
		}

		// 查询出当前登录用户所属公司信息 为0 则查询出全部
		List<ManageComp> compListSelect = manageCompMapper.getCompListBySelect(compId);
		//list转map
		Map<Integer, ManageComp> CompByIdMap = compListSelect.stream()
				.collect(Collectors.toMap(ManageComp::getCompId, a -> a));

		PageInfo<ManageCase> pageInfo = new PageInfo<>(manageCaseList);

		// 拿到所有的储物柜的MAC（编号）
		List<String> caseNos = manageCaseList.stream()
				.collect(Collectors.mapping(ManageCase::getCaseNo, Collectors.toList()));

		// 查询此公司柜子所有的收费类型
		List<ManageCaseType> caseTypeList = manageCaseTypeMapper.selectTypeByCompId(compId);
		Map<Integer, String> CaseTypeMap = caseTypeList.stream()
				.collect(Collectors.toMap(ManageCaseType::getTypeId, ManageCaseType::getName));

		ManageCaseBoxExample caseBoxExample = new ManageCaseBoxExample();
		//排序
		caseBoxExample.setOrderByClause("DOOR_NUM");
		//IS_DEL = 0 and  CASE_NO in (.... mac地址)
		caseBoxExample.createCriteria().andIsDelEqualTo((byte) 0).andCaseNoIn(caseNos);
		// 查询当前用户所有柜子下的所有箱子
		List<ManageCaseBox> manageCaseBoxList = manageCaseBoxMapper.selectByExample(caseBoxExample);
		Map<String, List<ManageCaseBox>> boxMapByCaseId = manageCaseBoxList.stream()
				.collect(Collectors.groupingBy(ManageCaseBox::getCaseNo, Collectors.toList()));
		
		//储物柜使用时限
		 ManageCaseUsetimeExample manageCaseUsetimeExample = new ManageCaseUsetimeExample();
		//CASE_NO in
		 manageCaseUsetimeExample.createCriteria().andCaseNoIn(caseNos);
		 List<ManageCaseUsetime> ManageCaseUsetimeList = manageCaseUsetimeMapper.selectByExample(manageCaseUsetimeExample);
		 Map<String, List<ManageCaseUsetime>> usetimeByCaseNo = ManageCaseUsetimeList.stream().collect(Collectors.groupingBy(ManageCaseUsetime::getCaseNo,Collectors.toList()));

		 // 循环填充完整数据
		if (!manageCaseList.isEmpty()) {
			for (int i = 0; i < manageCaseList.size(); i++) {
				int userNumber = 0;// 使用数量
				int closeNumber = 0;// 开启数量
				int total = 0;// 总数
				ManageCase manageCase = manageCaseList.get(i);

				List<ManageCaseBox> boxList = boxMapByCaseId.get(manageCase.getCaseNo()); //获取柜子对应的箱子
				Byte useType = manageCase.getUseType();
				CaseVO caseVO = DbByteToString.caseUseTypeToString(useType); // 用途编号转换为对应的文字 1->普通储物柜
				caseVO.setPlace(manageCase.getPlace()); // 柜子位置
				caseVO.setDes(manageCase.getDes()); 	// 描述
				caseVO.setId(manageCase.getId());  // id
				caseVO.setCaseNo(manageCase.getCaseNo()); // mac地址（编号）
				caseVO.setCaseNoBuy(manageCase.getCaseNoBuy()); // 商家自己所输入的编号
				Integer typeId = manageCase.getTypeId(); // 收费类型id
				caseVO.setIsBoxOfflineNotity(manageCase.getIsBoxOfflineNotity()); // 是否开启储物柜离线短信通知(1.是   0.否）
				caseVO.setBindPhoneNumber(manageCase.getBindPhoneNumber()); // 绑定的通知手机号BIND_PHONE_NUMBER
				if (typeId != null) {
					String string = CaseTypeMap.get(typeId); // 根据收费id获取到对应的收费类型
					caseVO.setType(string);
				}
				/*柜子所属公司id是否为空*/
				if (manageCase.getCompId() == null) {
					caseVO.setCompName("");
				} else {
					// 则获取所属公司的信息
					if (CompByIdMap.get(manageCase.getCompId()) != null) {
						//设置公司名称
						caseVO.setCompName(CompByIdMap.get(manageCase.getCompId()).getCompName());
					} else {
						caseVO.setCompName("");
					}
				}
				// 柜子是否在线 1 在线 0 否
				if (manageCase.getIsOnline() == 1) {
					caseVO.setIsOnline("是");
				} else {
					caseVO.setIsOnline("否");
				}
				// 柜子是否正常 1 正常
				if (manageCase.getIsNormal() == 1) {
					caseVO.setIsNormal("是");
				} else {
					caseVO.setIsNormal("否");
				}

				//柜子下对应的箱子是否为空 不为空则进入
				if (boxList != null && !boxList.isEmpty()) {
					total = boxList.size();
					for (int j = 0; j < boxList.size(); j++) {
						ManageCaseBox manageCaseBox = boxList.get(j); // 依次获取箱子
						if (manageCaseBox.getSwitchStatus() == 1) {// 1 开启状态 0 关闭状态
							closeNumber = closeNumber + 1; // 开启状态则给开启数量+1
						}
						if (manageCaseBox.getUseStatus() == 1) {//  1 被占用 0 空闲
 							userNumber = userNumber + 1; //占用数+1
						}
					}
				}

				caseVO.setIsSize(manageCase.getIsSize()); // 是否区分大中小柜(1.是   0.否）
				caseVO.setSwitchCase(closeNumber + "/" + total); // 开启数量/箱子总数
				caseVO.setBoxNumber(total); // 门总数
				caseVO.setUseCase(userNumber + "/" + total); // 使用数量/箱子总数
				caseVO.setList(compListSelect); // 所属公司信息
				/*储物柜使用时限*/
				if(usetimeByCaseNo.get(manageCase.getCaseNo()) != null){
					List<ManageCaseUsetime> manageCaseUsetimes = usetimeByCaseNo.get(manageCase.getCaseNo());
					String userEndTime = DateTimeHelper.formatDateTimetoString(manageCaseUsetimes.get(0).getUseEndTime(),"yyyy-MM-dd HH:mm"); // 使用截止时间
					caseVO.setUseEndTime(userEndTime);
				}
				list.add(caseVO);
			}
		}

		long count = pageInfo.getTotal();  //柜子总数
		LayUiResultJson<CaseVO> result = new LayUiResultJson<>(count, list);
		return result;
	}




	/**
	 * @param boxId
	 * @param size
	 * @return
	 * @author 周磊
	 * @since 2018年10月30日
	 */
	@ResponseBody
	@RequestMapping(value = "/changeSize", method = RequestMethod.GET)
	public AjaxResult changeSize(Integer boxId, Byte size, String caseNo) {
		ManageCaseExample example = new ManageCaseExample();
		example.createCriteria().andCaseNoEqualTo(caseNo);
		List<ManageCase> selectByExample = manageCaseMapper.selectByExample(example);
		if (!selectByExample.isEmpty()) {
			ManageCase manageCase = selectByExample.get(0);
			Byte isSize = manageCase.getIsSize();
			if (Byte.valueOf("1").equals(isSize)) {
				ManageCaseBox record = new ManageCaseBox();
				record.setSize(size);
				record.setId(boxId);
				int updateByPrimaryKeySelective = manageCaseBoxMapper.updateByPrimaryKeySelective(record);
				if (updateByPrimaryKeySelective != 0) {
					return new AjaxResult();
				} else {
					return new AjaxResult("修改失败!");
				}
			} else {
				return new AjaxResult("没有修改权限");
			}
		} else {
			return new AjaxResult("加载错误，请重试！！！");

		}
	}

	/**
	 * 拿到存储柜的箱子的列表
	 */
	@ResponseBody
	@RequestMapping(value = "/getCaseBoxList", method = RequestMethod.GET)
	public LayUiResultJson<CaseBoxListVO> getCaseBoxList(CaseBoxListParam param) {
		String caseNo = param.getCaseNo(); //柜子的mac地址
		List<CaseBoxListVO> list = new ArrayList<>();
		PageHelper.startPage(param.getPage(), param.getLimit(), true);

		ManageCaseBoxExample example = new ManageCaseBoxExample();
		example.setOrderByClause("DOOR_NUM");
		example.createCriteria().andCaseNoEqualTo(caseNo).andIsDelEqualTo((byte) 0);
		List<ManageCaseBox> boxList = manageCaseBoxMapper.selectByExample(example);
		PageInfo<ManageCaseBox> pageInfo = new PageInfo<>(boxList);
		boxList.stream().forEach(a -> {
			CaseBoxListVO caseBoxListVO = new CaseBoxListVO();
			caseBoxListVO.setCaseNo(param.getCaseNo());
			caseBoxListVO.setIsShow(a.getSwitchStatus());
			caseBoxListVO.setBoxId(a.getId());
			caseBoxListVO.setSize(a.getSize());
			caseBoxListVO.setDoorNum(a.getDoorNum());
			caseBoxListVO.setGoodsPrice(String.valueOf(a.getGoodsPrice()));
			Byte isConn = a.getIsConn();
			Byte switchStatus = a.getSwitchStatus();// 0.关 1.开
			Byte useStatus = a.getUseStatus();// 使用状态（0.空闲 1.占用）
			Byte isLocked = a.getIsLocked();// 是否关门（1.是 0.否）

			if (Byte.valueOf("1").equals(isLocked)) {
				caseBoxListVO.setIsLocked("是");
			} else {
				caseBoxListVO.setIsLocked("否");
			}
			if (Byte.valueOf("1").equals(isConn)) {
				caseBoxListVO.setIsConn("正常");
			} else {
				caseBoxListVO.setIsConn("异常");
			}
			if (Byte.valueOf("1").equals(switchStatus)) {
				caseBoxListVO.setSwitchStatusStr("开");
			} else {
				caseBoxListVO.setSwitchStatusStr("关");
			}
			if (Byte.valueOf("1").equals(useStatus)) {
				caseBoxListVO.setUseStatusStr("占用");
				caseBoxListVO.setSaveId(a.getUserId());
				caseBoxListVO.setSaveTimeStr(
						DateTimeHelper.formatDateTimetoString(a.getSaveTime(), DateTimeHelper.FMT_yyyyMMddHHmmss));
			} else {
				caseBoxListVO.setUseStatusStr("空闲");
				caseBoxListVO.setSaveId("--");
				caseBoxListVO.setSaveTimeStr("--");
			}
			list.add(caseBoxListVO);
		});
		long count = pageInfo.getTotal();
		LayUiResultJson<CaseBoxListVO> result = new LayUiResultJson<>(count, list);
		return result;
	}

	@ResponseBody
	@RequestMapping(value = "/changeCaseSize", method = RequestMethod.POST)
	public AjaxResult changeCaseSize(String caseNo, Byte size) {
		ManageUser user = UserContext.getUser();
		Integer compId = user.getCompId();
		if (compId.equals(0)) {
			ManageCase record = new ManageCase();
			record.setIsSize(size);
			ManageCaseExample example = new ManageCaseExample();
			example.createCriteria().andCaseNoEqualTo(caseNo);

			int updateByExampleSelective = manageCaseMapper.updateByExampleSelective(record, example);
			if (updateByExampleSelective == 0) {
				return new AjaxResult("权限不足，修改失败");
			}
			return new AjaxResult();
		} else {
			return new AjaxResult("权限不足，修改失败");
		}
	}

	/**
	 * 拿到箱子的使用记录
	 *
	 * @param param
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getBoxUseRecord", method = RequestMethod.GET)
	public LayUiResultJson<BoxUseRecordVO> getBoxUseRecord(BoxUseRecordParam param) {
		Integer boxId = param.getBoxId();
		ManageCaseBox manageCaseBox = manageCaseBoxMapper.selectByPrimaryKey(boxId);
		String caseNo = manageCaseBox.getCaseNo();
		ManageCaseExample example = new ManageCaseExample();
		example.createCriteria().andCaseNoEqualTo(caseNo);
		List<ManageCase> selectByExample = manageCaseMapper.selectByExample(example);
		ManageCase manageCase = selectByExample.get(0);
		Byte useType = manageCase.getUseType();

		List<BoxUseRecordVO> list = new ArrayList<>();
		PageHelper.startPage(param.getPage(), param.getLimit(), true);
		List<AccessRecord> recordList = accessRecordMapper.getRecordByBoxId(param);
		PageInfo<AccessRecord> pageInfo = new PageInfo<>(recordList);
		long count = pageInfo.getTotal();
		recordList.stream().forEach(a -> {
			Byte type = a.getType();// 类型（1.存 2.取 ）
			BoxUseRecordVO boxUseRecordVO = DbByteToString.accessRecordTypeToString(type);
			Byte source = a.getSource();
			if (Byte.valueOf("1").equals(source)) {
				boxUseRecordVO.setIsManager("是");
			} else {
				boxUseRecordVO.setIsManager("否");
			}
			if (CaseUseTypeConst.EXPRESS_CASE.equals(useType) && AllConst.ACCESS_RECORD_TYPE.SAVE_TYEP.equals(type)) {
				boxUseRecordVO.setUsePerson(a.getUserId() + "(" + a.getPhone() + ")");
			} else {
				boxUseRecordVO.setUsePerson(a.getUserId());
			}
			boxUseRecordVO.setUseTime(
					DateTimeHelper.formatDateTimetoString(a.getCreateTime(), DateTimeHelper.FMT_yyyyMMddHHmmss));
			boxUseRecordVO.setSource(a.getSource());
			list.add(boxUseRecordVO);
		});
		LayUiResultJson<BoxUseRecordVO> result = new LayUiResultJson<>(count, list);

		return result;
	}

	/**
	 * @return 柜子清除
	 */
	@SystemControllerLog(description = "箱子的清除操作")
	@ResponseBody
	@RequestMapping(value = "/boxClear", method = RequestMethod.GET)
	public AjaxResult boxClear(@ApiParam(required = true, name = "boxId", value = "箱子Id") Integer boxId) {
		ManageCaseBox manageCaseBox = manageCaseBoxMapper.selectByPrimaryKey(boxId);
		Byte useStatus = manageCaseBox.getUseStatus();
		Byte saveSource = manageCaseBox.getSaveSource();// 1.微信公众号 2.微信小程序
		String caseNo = manageCaseBox.getCaseNo();

		ManageCaseExample example = new ManageCaseExample();
		example.createCriteria().andCaseNoEqualTo(caseNo);
		List<ManageCase> selectByExample = manageCaseMapper.selectByExample(example);
		ManageCase manageCase = selectByExample.get(0);

		if (Byte.valueOf("1").equals(useStatus)) {
			try {
				manageCaseBoxService.boxClear(manageCaseBox, manageCase);
				if (Byte.valueOf("1").equals(saveSource)) {// 消除成功后----如果是微信公众号，，，发送消息
					// 清除成功后，发送微信消息
					manageCaseService.getToken();
					MessageTemplate messageTemplate = new MessageTemplate();
					messageTemplate.setTouser(manageCaseBox.getUserId());
					MessageData data = new MessageData();
					DetailDate first = new DetailDate();// #8B2500
					first.setColor("#8B2500");
					first.setValue("您好，您使用储物柜因超时已被清理");
					data.setFirst(first);
					DetailDate keyword1 = new DetailDate();
					keyword1.setColor("#8B2500");
					keyword1.setValue(manageCase.getPlace());
					data.setKeyword1(keyword1);
					DetailDate keyword2 = new DetailDate();
					keyword2.setColor("#8B2500");
					keyword2.setValue(manageCaseBox.getDoorNum() + "号门");
					data.setKeyword2(keyword2);
					DetailDate keyword3 = new DetailDate();
					keyword3.setColor("#8B2500");
					keyword3.setValue(
							DateTimeHelper.formatDateTimetoString(manageCaseBox.getSaveTime(), "yyyy-MM-dd HH:mm:ss"));
					data.setKeyword3(keyword3);
					DetailDate remar = new DetailDate();
					remar.setColor("#8B2500");
					remar.setValue("如有疑问，请尽快联系管理员,并取回自己的物品！！！");
					data.setRemark(remar);
					messageTemplate.setData(data);
					String jsonString = JSONObject.toJSONString(messageTemplate);

					SysConstExample sysExample = new SysConstExample();
					example.createCriteria().andNameEqualTo("ACCESS_TOKEN");
					List<SysConst> sysConst = sysConstMapper.selectByExample(sysExample);
					String accessToken = sysConst.get(0).getValue();
					String url = WeiXinConst.MESSAGE_TEMPLATE.replace("ACCESS_TOKEN", accessToken);
					HttpClientUtil.httpPost(url, jsonString);
				}
				return new AjaxResult();
			} catch (Exception e) {
				e.printStackTrace();
				return new AjaxResult("清除失败");
			}
		} else {
			return new AjaxResult();
		}

	}

	/**
	 * @param status
	 *            : 0.关 1.开',
	 * @return 柜子启用或关闭
	 */
	@SystemControllerLog(description = "柜子启用或关闭操作")
	@ResponseBody
	@RequestMapping(value = "/boxOpenOrClose", method = RequestMethod.GET)
	public AjaxResult boxOpenOrClose(@ApiParam(required = true, name = "boxId", value = "箱子Id") Integer boxId,
			@ApiParam(required = true, name = "status", value = "状态 0.关   1.开") Byte status) {
		ManageCaseBox record = new ManageCaseBox();
		record.setId(boxId);
		record.setSwitchStatus(status);
		ManageCaseBox selectByPrimaryKey = manageCaseBoxMapper.selectByPrimaryKey(boxId);
		Byte useStatus = selectByPrimaryKey.getUseStatus();

		if (Byte.valueOf("1").equals(useStatus)) {
			return new AjaxResult("使用中，关闭失败");
		} else {
			try {
				int updateByPrimaryKeySelective = manageCaseBoxMapper.updateByPrimaryKeySelective(record);
				if (updateByPrimaryKeySelective == 1) {
					return new AjaxResult();
				} else {
					return new AjaxResult("关闭失败");
				}
			} catch (Exception e) {
				return new AjaxResult("关闭失败");
			}
		}
	}

	@SystemControllerLog(description = "储物柜的位置，编号等修改")
	@ResponseBody
	@RequestMapping(value = "/BoxChange", method = RequestMethod.POST)
	public AjaxResult boxChange(ChangeCaseParam param) {
		
		System.out.println(param.toString());
		Integer compId = param.getCompId();
		Integer selectTypeId = param.getTypeId();
		ManageCase box = new ManageCase();
		box.setCaseNoBuy(param.getCaseNoBuy());
		box.setDes(param.getDes());
		box.setPlace(param.getPlace());
		box.setUseType(param.getUseType());
		box.setIsBoxOfflineNotity(param.getIsBoxOfflineNotity()==null?(byte)0:(byte)1);
		box.setBindPhoneNumber(param.getBindPhoneNumber());
		if (compId != null) {
			box.setCompId(compId);
			if (selectTypeId == null || selectTypeId.equals(-1)) {
				ManageCaseTypeExample example = new ManageCaseTypeExample();
				example.createCriteria().andCompIdEqualTo(compId).andIsDefaultEqualTo((byte) 1);
				List<ManageCaseType> selectByExample = manageCaseTypeMapper.selectByExample(example);
				if (!selectByExample.isEmpty()) {
					ManageCaseType manageCaseType = selectByExample.get(0);
					Integer typeId = manageCaseType.getTypeId();
					box.setTypeId(typeId);
				} else {
					return new AjaxResult("请选择类型或设置默认类型");
				}
			} else {
				box.setTypeId(selectTypeId);
			}
		}
		String caseNo = param.getCaseNo();
		ManageCaseExample example = new ManageCaseExample();
		example.createCriteria().andCaseNoEqualTo(caseNo);
		manageCaseMapper.updateByExampleSelective(box, example);
		//strCode储物使用时限，结束时间
		ManageCaseUsetimeExample CaseNoEq = new ManageCaseUsetimeExample();
		CaseNoEq.createCriteria().andCaseNoEqualTo(caseNo);
		long countByExample = manageCaseUsetimeMapper.countByExample(CaseNoEq);
		ManageCaseUsetime manageCaseUsetime = new ManageCaseUsetime();
		if(countByExample == 0){
			manageCaseUsetime.setCaseNo(caseNo);
			manageCaseUsetime.setUseEndTime(param.getUseEndTime());
			manageCaseUsetime.setCreateTime(new Date());
			manageCaseUsetimeMapper.insertSelective(manageCaseUsetime);
		}else{
			manageCaseUsetime.setCaseNo(caseNo);
			manageCaseUsetime.setUseEndTime(param.getUseEndTime());
			manageCaseUsetimeMapper.updateUseEndTimeByCaseNo(manageCaseUsetime);
		}
		//endCode储物使用时限，结束时间
		try{
			RbMsgCommand rbMsgCommand = new RbMsgCommand();
			rbMsgCommand.setType(RbMsgCommand.NOTIFY_SYNCHRODATA);
			RabbitSendMessage.send(caseNo, rbMsgCommand);
		}catch(Exception ex){
			ex.printStackTrace();
		}

		return new AjaxResult();
	}

	@SystemControllerLog(description = "管理员开箱操作")
	@ResponseBody
	@RequestMapping(value = "/openBoxByAdmin", method = RequestMethod.GET)
	public AjaxResult openBoxByAdmin(@ApiParam(required = true, name = "caseNo", value = "储物柜的MAC值") String caseNo,
			@ApiParam(required = true, name = "boxNum", value = "第几号门") Integer boxNum)
			throws IOException, TimeoutException {
		
		System.err.println("管理员开箱操作");
		
		ManageUser user = UserContext.getUser();
		String loginName = user.getLoginName(); // 登录名称
		Map<String, Object> sendMap = new HashMap<>();
		sendMap.put("door", boxNum);
		sendMap.put("timestamp", new Date().getTime());
		ObjectMapper mapper = new ObjectMapper();
		String writeValueAsString = mapper.writeValueAsString(sendMap); // 序列化为json

		try {
			manageCaseBoxService.addRecorByAdmin(caseNo, boxNum, loginName); // 写入一条开箱记录

			Connection connection = ConnectionUtils.getConnection(); // mq 连接
			Channel channel = connection.createChannel();
			Map<String, Object> args = new HashMap<String, Object>();
			args.put("x-message-ttl", 40000);
			System.out.println(caseNo);
			// queue 队列名, durable 是否持久化, exclusive 是否专属,  autoDelete 是否自动删除, arguments  队列参数
			channel.queueDeclare(caseNo, true, false, false, args); // 声明一个队列 队列名为mac地址
			System.out.println(writeValueAsString);
			//交换器   路由键   消息的其它属性  消息体
			channel.basicPublish("", caseNo, null, writeValueAsString.getBytes()); // 发送消息
			channel.close();
			connection.close();
			return new AjaxResult();

		} catch (Exception e) {
			return new AjaxResult("开箱失败请重试");
		}

	}

	/**
	 * @param caseNo
	 * @return 一键开门
	 */
	@ResponseBody
	@RequestMapping("/box/openAll")
	public AjaxResult boxOpenAll(String caseNo) throws JsonProcessingException {
		ManageUser user = UserContext.getUser();
		Map<String, Object> sendMap = new HashMap<>();
		sendMap.put("openAll", 1);
		sendMap.put("timestamp", new Date().getTime());
		ObjectMapper mapper = new ObjectMapper();
		String writeValueAsString = mapper.writeValueAsString(sendMap);
		try {
			Connection connection = ConnectionUtils.getConnection();
			Channel channel = connection.createChannel();
			Map<String, Object> args = new HashMap<String, Object>();
			args.put("x-message-ttl", 40000);
			channel.queueDeclare(caseNo, true, false, false, args);
			channel.basicPublish("", caseNo, null, writeValueAsString.getBytes());
			channel.close();
			connection.close();

			ManageCaseBoxExample example = new ManageCaseBoxExample();
			example.createCriteria().andCaseNoEqualTo(caseNo);
			List<ManageCaseBox> boxList = manageCaseBoxMapper.selectByExample(example);

			AccessRecord accessRecord = new AccessRecord();
			accessRecord.setCreateTime(new Date());
			accessRecord.setCreateDay(DateTimeHelper.formatDateTimetoString(new Date(), "yyyy-MM-dd"));
			accessRecord.setSource((byte) 1);
			accessRecord.setType((byte) 5);
			accessRecord.setUserId(user.getLoginName());

			boxList.stream().forEach(a -> {
				accessRecord.setBoxId(a.getId());
				accessRecordMapper.insertSelective(accessRecord);
			});

			return new AjaxResult();
		} catch (Exception e) {
			return new AjaxResult("开门指令发送失败");
		}
	}

	/**
	 * @param boxIds
	 * @return 批量清除
	 * @throws Exception
	 * @author liuCheng
	 * @since 2018年12月18日 下午12:49:54
	 */
	@ResponseBody
	@RequestMapping("/boxClearBatch")
	public AjaxResult boxClearBatch(String boxIds) throws Exception {

		List<String> asList = Arrays.asList(boxIds.split(","));
		List<Integer> boxIdList = asList.stream().map(Integer::parseInt).collect(Collectors.toList());

		// 查询到这些箱子的使用情况
		ManageCaseBoxExample selectManageCaseBoxExample = new ManageCaseBoxExample();
		selectManageCaseBoxExample.createCriteria().andIdIn(boxIdList).andUseStatusEqualTo((byte) 1);
		List<ManageCaseBox> manageCaseBoxList = manageCaseBoxMapper.selectByExample(selectManageCaseBoxExample);
		if (!manageCaseBoxList.isEmpty()) {
			// 1.普通用途 2.医用床 3.快递柜 4.快餐 5.成人用品柜 6.智能医药柜 7.售卖机

			String caseNo = manageCaseBoxList.get(0).getCaseNo();
			ManageCaseExample manageCaseExample = new ManageCaseExample();
			manageCaseExample.createCriteria().andCaseNoEqualTo(caseNo);
			List<ManageCase> selectByExample = manageCaseMapper.selectByExample(manageCaseExample);
			ManageCase manageCase = selectByExample.get(0);
			Byte useType = manageCase.getUseType();
			if (Byte.valueOf("3").equals(useType)) {// 快递柜单独处理
				List<Integer> collect = manageCaseBoxList.stream()
						.collect(Collectors.mapping(ManageCaseBox::getId, Collectors.toList()));
				ManageUser user = UserContext.getUser();
				String loginName = user.getLoginName();
				try {
					manageCaseBoxService.clearBoxByExpress(collect, loginName);
					return new AjaxResult();
				} catch (Exception e) {
					return new AjaxResult("清除失败");
				}

			} else {
				// 获取收费类型
				Integer typeId = manageCase.getTypeId();
				ManageCaseType manageCaseType = manageCaseTypeMapper.selectByPrimaryKey(typeId);
				try {
					manageCaseBoxService.boxClearBatch(manageCaseBoxList, manageCase, manageCaseType);
					return new AjaxResult();
				} catch (Exception e) {
					return new AjaxResult("清除失败");
				}
			}
		} else {
			return new AjaxResult();

		}

	}
	
	@ResponseBody
	@Transactional
	@RequestMapping(value = "/boxReplace", method = RequestMethod.POST)
	public AjaxResult boxReplace(String beReplacedCaseNo, String replacementCaseNo) {
		try{
			
			System.err.println(beReplacedCaseNo+"    "+replacementCaseNo);
			ManageCaseExample manageCaseExample = new ManageCaseExample();
			manageCaseExample.createCriteria().andCaseNoEqualTo(replacementCaseNo);
			//删除  替换的储物柜
			manageCaseMapper.deleteByExample(manageCaseExample);
			//修改被替换的caseNo为替换的caseNo
			ManageCaseExample manageCaseExampleByReplace = new ManageCaseExample();
			manageCaseExampleByReplace.createCriteria().andCaseNoEqualTo(beReplacedCaseNo);
			ManageCase mc = new ManageCase();
			mc.setCaseNo(replacementCaseNo);
			manageCaseMapper.updateByExampleSelective(mc, manageCaseExampleByReplace);
			
			ManageCaseBoxExample boxExample = new ManageCaseBoxExample();
			boxExample.createCriteria().andCaseNoEqualTo(replacementCaseNo).andIsDelEqualTo((byte) 0);;
			ManageCaseBox mcb = new ManageCaseBox();
			mcb.setIsDel((byte)1);
			manageCaseBoxMapper.updateByExampleSelective(mcb, boxExample);
			
			//将替换的mac 修改为被替换的mac
			ManageCaseBox record = new ManageCaseBox();
			ManageCaseBoxExample boxExample2 = new ManageCaseBoxExample();
			boxExample2.createCriteria().andCaseNoEqualTo(beReplacedCaseNo);
			record.setCaseNo(replacementCaseNo);
			manageCaseBoxMapper.updateByExampleSelective(record, boxExample2);
			
		}catch(Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return new AjaxResult("更换失败");
		}
		return  new AjaxResult();
	}
	
	@ResponseBody
	@RequestMapping(value = "/getBoxInfo", method = RequestMethod.POST)
	public Object getBoxinfo(String caseNo) {
		try{
			List<BoxAllInfoVO> boxList = manageCaseBoxMapper.selectAllBoxInfoByCaseNo(caseNo);
			Object json = JSONObject.toJSON(boxList);
			return  json;
		}catch(Exception e){
			return null;
		}
	}
	
	@ResponseBody
	@RequestMapping(value = "/setBoxInfo", method = RequestMethod.POST)
	public AjaxResult setBoxinfo(String caseNo,String place,String caseNoBuy,Integer compId,Integer typeId,Integer isSize ) {
		try{
			System.err.println(caseNo);
			ManageCase manageCase = new ManageCase();
			ManageCaseExample manageCaseExample = new ManageCaseExample();
			manageCaseExample.createCriteria().andCaseNoEqualTo(caseNo);
			manageCase.setPlace(ToolsUtils.valueOfNull(place));
			manageCase.setCaseNoBuy(ToolsUtils.valueOfNull(caseNoBuy));
			manageCase.setCompId(compId);
			manageCase.setTypeId(typeId);
			if(isSize!=null){
				manageCase.setIsSize((byte) isSize.intValue());
			}
			System.out.println(String.valueOf(manageCase));
			manageCaseMapper.updateByExampleSelective(manageCase, manageCaseExample);
			AjaxResult ajaxResult = new AjaxResult();
			ajaxResult.setMessage("添加成功");
			ajaxResult.setSuccess(true);
			return ajaxResult;
		}catch(Exception e){
			System.out.println("修改失败");
			e.printStackTrace();
			return new AjaxResult("修改失败");
		}
	}
}
